<template>
  <div class="system-edit-user-container">

    <el-card width="769px">
      <template #header v-if="!isView">
        <z-detail-page-header
            class="page-header"
            style="margin: 5px 0;"
            @back="goBack">
        </z-detail-page-header>
      </template>

      <template #content>
        <span style="padding-right: 10px;">{{ editType === 'save' ? '新增申请' : '更新申请' }}</span>
      </template>
      <el-card>
        <div>
          <el-steps :active="2" style="font-size: 1px;width: 80%" v-if="editType==='detail'" align-center>
            <el-step title="周武" :icon="SuccessFilled" description="申请人"/>
            <el-step title="张三" :icon="SuccessFilled" description="二级审批"/>
            <el-step title="李四" :icon="SuccessFilled" description="三级审批"/>
          </el-steps>
        </div>
        <h3 style="margin: 20px">基础信息</h3>
        <el-form :model="state.form" :rules="state.rules" ref="userFormRef" size="default" label-width="90px" inline>
          <el-row :gutter="0">
            <el-row>
              <el-form-item label="申请名称2" prop="name" style="width: 650px;margin-right:80px">
                <el-input :disabled="state.editType==='update'" v-model="state.form.userApply.name"
                          placeholder="请输入申请名称"
                          clearable></el-input>
              </el-form-item>
              <el-form-item prop="name">
                <el-radio-group v-model="state.form.userApply.type">
                  <el-radio :label="10">工作类</el-radio>
                  <el-radio :label="20">行为类</el-radio>
                  <el-radio :label="30">其他类</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="奖扣日期" prop="award_deduction_date">
                <DateTimePicker v-model="state.form.userApply.award_deduction_date"/>
              </el-form-item>
              <el-form-item label="审核人" prop="auditor" style="width: 310px">
                <el-input v-model="state.form.userApply.auditor" placeholder="请输入" clearable></el-input>
              </el-form-item>
              <el-form-item label="标签" prop="label" style="width: 310px">
                <el-input v-model="state.form.userApply.label" placeholder="请输入" clearable></el-input>
              </el-form-item>
            </el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="参与人" style="margin-top: 30px">
                <z-table
                    :columns="state.columns"
                    :data="state.form.userApply.userApplyDetails"
                    ref="tableRef"
                    v-model:page-size="state.listQuery.pageSize"
                    v-model:page="state.listQuery.page"
                    :total="state.total"
                    :showPage="false"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <el-form-item label="备注" prop="remark" style="width: 1000px">
                <el-input v-model="state.form.userApply.remark" type="textarea" placeholder="请输入用户描述"
                          maxlength="150"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="editType!=='detail'">
              <el-form-item style="margin-left: 90px">
                <template v-for="item in state.approveTypes">
                  <el-button v-if="item.type==='edit' && state.form.userApply.status ===50"
                             type="primary"
                             :key="item" @click="saveOrUpdate(item)">
                    {{ item.name }}
                  </el-button>
                </template>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="editType==='detail'">
              <el-form-item style="margin-left: 90px">
                <template v-for="item in state.approveTypes">
                  <el-button v-if="item.type==='detail' && state.form.userApply.status !==50"
                             type="primary"
                             :key="item" @click="saveOrUpdate(item)">
                    {{ item.name }}
                  </el-button>
                </template>
                <!--                <el-button type="primary" @click="saveOrUpdate('allow')">同 意</el-button>-->
                <!--                <el-button type="primary" @click="saveOrUpdate('disallowed')">拒 绝</el-button>-->
                <!--                <el-button type="primary" @click="saveOrUpdate('undo')">撤 销</el-button>-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-card>
  </div>
</template>

<script setup name="EditUserApply">
import {computed, h, onMounted, reactive, ref} from 'vue';
import {myApplyApi} from "/@/api/point_management/my_application";
import {ElButton, ElMessage, ElInput, ElSelect, ElOption} from "element-plus";
import {Plus, Minus, CopyDocument, SuccessFilled} from '@element-plus/icons'
import {useRoute} from 'vue-router'
import {formatDate} from "/@/utils/formatTime";
import DateTimePicker from "/@/components/dateTimePicker/index.vue"

const props = defineProps({
  isView: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  editType: {
    type: String,
    default: () => {
      return '';
    },
  },
});

const emit = defineEmits(["getList"])

const tableRef = ref();
const defaultTime = formatDate(new Date(), "YYYY-mm-dd HH:MM:SS")
const point_levels = ref([
  {label: 'A分', value: 10},
  {label: 'B分', value: 20},
])
const award_deduction_types = ref([
  {label: '奖励分', value: 10},
  {label: '扣除分', value: 20},
])

const createForm = () => {
  return {
    userApply: {
      userApplyDetails: [
        {
          apply_id: null,
          apply_user_id: null,
          participant_user_id: 1,
          participant_user_name: "周武",
          participant_user_number: "666666",
          point_level: 10,
          award_deduction_type: 10,
          award_deduction_value: 45,
        }, {
          apply_id: null,
          apply_user_id: null,
          participant_user_id: 2,
          participant_user_name: "赵军",
          participant_user_number: "777777",
          point_level: 20,
          award_deduction_type: 20,
          award_deduction_value: 10,
        }
      ],
      id: null,
      name: "事件名称",
      user_name: "赵军",
      type: 10,
      status: 10,
      label: "出差申请",
      award_deduction_date: defaultTime,
      remark: "我是一个备注"
    }
  }
}

const userFormRef = ref()
const state = reactive({
  columns: [
    {
      key: 'participant_user_name', label: '员工姓名', width: '100px', align: 'center', show: true,
      render: ({row}) => h(ElInput, {
        link: true,
        type: "primary",
        placeholder: "请输入员工姓名",
        modelValue: row.participant_user_name,
        "onUpdate:modelValue": ($event) => {
          emit("updateMsg", $event)
        }
      })
    },
    {
      key: 'participant_user_number', label: '员工工号', width: '100px', align: 'center', show: true,
      render: ({row}) => h(ElInput, {
        link: true,
        type: "primary",
        placeholder: "请输入员工工号",
        modelValue: row.participant_user_number,
        "onUpdate:modelValue": ($event) => {
          emit("updateMsg", $event)
        }
      })
    },
    {
      key: 'point_level', label: '积分等级', width: '150px', align: 'center', show: true,
      render: ({row}) => h(ElSelect, {
        class: 'w100',
        placeholder: '请选择',
        modelValue: row.point_level,
        'onUpdate:modelValue': (value) => {
          row.point_level = value;
        },
      }, () => point_levels.value?.map(item => {
        return h(ElOption, {label: item.label, value: item.value});
      }))
    },
    {
      key: 'award_deduction_type', label: '奖扣类型', width: '150px', align: 'center', show: true,
      render: ({row}) => h(ElSelect, {
        class: 'w100',
        placeholder: '请选择',
        modelValue: row.award_deduction_type,
        'onUpdate:modelValue': (value) => {
          row.award_deduction_type = value;
        },
      }, () => award_deduction_types.value?.map(item => {
        return h(ElOption, {label: item.label, value: item.value});
      }))
    }, {
      key: 'award_deduction_value', label: '奖扣分值', width: '150px', align: 'center', show: true,
      render: ({row}) => h(ElInput, {
        link: true,
        type: "primary",
        placeholder: "请输入奖扣分",
        modelValue: row.award_deduction_value,
        "onUpdate:modelValue": ($event) => {
          emit("updateMsg", $event)
        }
      })
    },
    {
      label: '操作', fixed: 'right', width: '260px', align: 'center', style: 'el-icon-plus',
      render: ({row, $index}) => h("div", null, [
        h(ElButton, {
          type: "button",
          icon: Plus,
          onClick: () => {
            operateTableRow("add")
          }
        }),
        h(ElButton, {
          type: "button",
          icon: CopyDocument,
          onClick: () => {
            operateTableRow("copy", row)
          }
        }),
        h(ElButton, {
          type: "button",
          icon: Minus,
          onClick: () => {
            operateTableRow("del", row, $index)
          }
        })
      ]),
    },
  ],
  listData: [],
  tableLoading: false,
  total: 0,
  listQuery: {
    page: 1,
    pageSize: 20,
    name: '',
    id: '',
  },
  isShowDialog: false,
  editType2: '',
  form: createForm(),
  rules: {
    userApply: {
      name: [{required: true, message: '请输入申请名称', trigger: 'blur'},],
      type: [{required: true, message: '请选择申请类型', trigger: 'blur'},],
    }
  },

  approveTypes: [
    {name: "同意", approveType: 30, type: 'detail'},
    {name: "拒绝", approveType: 40, type: 'detail'},
    {name: "撤销", approveType: 50, type: 'detail'},
    {name: "提交", approveType: 10, type: 'edit'},
    {name: "草稿", approveType: 20, type: 'edit'},
  ]
});

const route = useRoute()
const editType = route.query.editType
const apply_id = computed(() => {
  return route.query.id || null
})


// 更新状态30，同意 40，不同意 50撤销
const saveOrUpdate = async (approveType) => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      state.form.userApply.id = apply_id
      state.form.userApply.status = approveType.approveType
      if (approveType.type === 'detail') {
        await myApplyApi().userApplyApprove(state.form.userApply)
      } else {
        await myApplyApi().userApplySaveOrUpdate(state.form)
      }
      ElMessage.success('操作成功');
      emit('getList')
    } else {
      ElMessage.error('提交失败');
    }
  })
};


// goBack
const goBack = () => {
  router.push({name: 'userApply'})
}

// 初始化表格数据
const detail = () => {
  if (!apply_id.value) return false;
  state.listQuery.id = apply_id.value
  tableRef.value.openLoading()
  myApplyApi().userApplyDetail(state.listQuery)
      .then(res => {
        state.form.userApply = res.data
        state.total = res.data.rowTotal
      })
      .finally(() => {
        tableRef.value.closeLoading()
      })
};

const operateTableRow = (editType, row, index) => {
  // tableRef.value.openLoading()
  if (editType === 'add') {
    // console.log('row:', row, 'editType:', editType, 'apply_user_info:', state.form.userApply.apply_user_info)
    // state.form.userApply.apply_user_info.push(state.form.userApply.apply_user_info[0])
    state.form.userApply.userApplyDetails.push({
      apply_id: null,
      apply_user_id: null,
      participant_user_id: null,
      participant_user_name: null,
      participant_user_number: null,
      point_level: null,
      award_deduction_type: null,
      award_deduction_value: null,
    })
  } else if (editType === 'copy') {
    // state.form.userApply.apply_user_info.push(Object.assign({}, row))
    state.form.userApply.userApplyDetails.push(JSON.parse(JSON.stringify(row)))
  } else if (editType === 'del') {
    state.form.userApply.userApplyDetails.splice(index, 1)
    // state.form.userApply.apply_user_info.splice(row,1)
  }
}

onMounted(() => {
  detail();
});

</script>
<style scoped>

.table_header_class {
  background-color: #a9dbfb;
}

:deep(.el-input__inner) {
  border-color: #ffffff;
}
</style>
